package com.hw.nio.echo;

import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;

public class EchoClient {

    /**
     * 1、打开socketChannel，绑定端口号
     * 2、注册selector，添加连接事件
     * 2、连接服务端，连接成功后，添加写入事件，向服务端发送数据
     * 3、发送完数据后添加读事件
     * 4、读事件中获取服务端返回的数据
     * 5、再添加写事件
     * 6、加个睡眠，别执行太快
     *
     * @throws IOException
     */
    @Test
    public void test() throws IOException, InterruptedException {
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.bind(new InetSocketAddress(8888));
        socketChannel.configureBlocking(false);

        socketChannel.connect(new InetSocketAddress(6666));
        Selector selector = Selector.open();
        socketChannel.register(selector, SelectionKey.OP_CONNECT);
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        while (true) {
            int select = selector.select();
            if (select > 0) {
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                SelectionKey selectionKey = iterator.next();
                iterator.remove();
                if (selectionKey.isConnectable()) {
                    socketChannel.finishConnect();
                    selectionKey.interestOps(SelectionKey.OP_WRITE);
                } else if (selectionKey.isWritable()) {
                    if (socketChannel.isConnected()) {
                        socketChannel.write(ByteBuffer.wrap(("心跳感应~~~" + System.currentTimeMillis()).getBytes(StandardCharsets.UTF_8)));
                        selectionKey.interestOps(SelectionKey.OP_READ);
                    }
                } else if (selectionKey.isReadable()) {
                    SocketChannel channel = (SocketChannel) selectionKey.channel();
                    channel.read(buffer);
                    buffer.flip();
                    byte[] serverResponse = new byte[buffer.remaining()];
                    buffer.get(serverResponse);
                    buffer.clear();
                    System.out.println("服务器发回数据：" + new String(serverResponse, StandardCharsets.UTF_8));
                    selectionKey.interestOps(SelectionKey.OP_WRITE);
                    Thread.sleep(1000);
                }
            }

        }

    }
}
